{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install azure-ai-language-conversations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ConversationAnalysisClient 用于分析现有的对话内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from azure.core.credentials import AzureKeyCredential\n",
    "from azure.ai.language.conversations.authoring import ConversationAuthoringClient\n",
    "\n",
    "endpoint = \"https://clu-chatbot-devtest.cognitiveservices.azure.cn/\"\n",
    "credential = AzureKeyCredential(key=\"4e367352ad354ead9178b55d1c1a8692\")\n",
    "\n",
    "client = ConversationAuthoringClient(endpoint, credential)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open (\"EmailAppDemo.json\"  , \"r\") as f:\n",
    "    test_data = json.load(f)\n",
    "\n",
    "with open (\"config_train.json\"  , \"r\") as f:\n",
    "    config = json.load(f)\n",
    "\n",
    "with open (\"analyze_task.json\"  , \"r\") as f:\n",
    "    analyze_task = json.load(f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "python pdf2zh/pdf2docx_cli.py --input /path/to/input.pdf --output /path/to/output.docx --pages 1-5 --debug"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [],
   "source": [
    "project_name = \"my-project\"\n",
    "deployment_name = \"my-deployment\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [],
   "source": [
    "job=client.begin_import_project(\n",
    "    project_name=project_name,\n",
    "    project=test_data\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'32723232-46fc-47c3-b5d6-93d1e7534a81_638602272000000000'"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "job.result()['jobId']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'jobId': '32723232-46fc-47c3-b5d6-93d1e7534a81_638602272000000000',\n",
       " 'createdDateTime': '2024-08-26T01:57:51Z',\n",
       " 'lastUpdatedDateTime': '2024-08-26T01:57:52Z',\n",
       " 'expirationDateTime': '2024-09-02T01:57:51Z',\n",
       " 'status': 'succeeded'}"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.get_import_project_job_status(\n",
    "    project_name=project_name,\n",
    "    job_id=job.result()['jobId']\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [],
   "source": [
    "training_job=client.begin_train(\n",
    "    project_name=project_name,\n",
    "    configuration=config\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'result': {'modelLabel': 'str',\n",
       "  'trainingConfigVersion': '2022-09-01',\n",
       "  'trainingMode': 'standard',\n",
       "  'trainingStatus': {'percentComplete': 100,\n",
       "   'startDateTime': '2024-08-26T01:21:12.9927188Z',\n",
       "   'endDateTime': '2024-08-26T01:21:29.582019Z',\n",
       "   'status': 'succeeded'},\n",
       "  'evaluationStatus': {'percentComplete': 100,\n",
       "   'startDateTime': '2024-08-26T01:21:30.74587Z',\n",
       "   'endDateTime': '2024-08-26T01:22:04.4813109Z',\n",
       "   'status': 'succeeded'}},\n",
       " 'jobId': 'd7fcf95b-2888-49d0-9491-4a1d7dfb477c_638602272000000000',\n",
       " 'createdDateTime': '2024-08-26T01:21:10Z',\n",
       " 'lastUpdatedDateTime': '2024-08-26T01:22:31Z',\n",
       " 'expirationDateTime': '2024-09-02T01:21:10Z',\n",
       " 'status': 'succeeded',\n",
       " 'warnings': [{'code': 'Warning',\n",
       "   'message': 'Entity `FromRelationshipName` is tagged in `9` training dataset examples, it is recommended to have `10` tags for better model quality.'},\n",
       "  {'code': 'Warning',\n",
       "   'message': 'Entity `PositionReference` is tagged in `8` training dataset examples, it is recommended to have `10` tags for better model quality.'}]}"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.get_training_job_status(\n",
    "    project_name=project_name,\n",
    "    job_id=\"d7fcf95b-2888-49d0-9491-4a1d7dfb477c_638602272000000000\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [],
   "source": [
    "deployment = client.begin_deploy_project(\n",
    "    project_name=project_name,\n",
    "    deployment_name=\"my-deployment\",\n",
    "    deployment={\n",
    "        \"trainedModelLabel\": \"str\"\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'deploymentName': 'my-deployment',\n",
       " 'modelId': 'str-20240826T012231-2038a8cb82594541a0f3dad3b3dfa673',\n",
       " 'lastTrainedDateTime': '2024-08-26T01:22:31.0931633Z',\n",
       " 'lastDeployedDateTime': '2024-08-26T01:58:19Z',\n",
       " 'deploymentExpirationDate': '2026-08-26',\n",
       " 'modelTrainingConfigVersion': '2022-09-01'}"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deployment.result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'deploymentName': 'my-deployment',\n",
       " 'modelId': 'str-20240826T012231-2038a8cb82594541a0f3dad3b3dfa673',\n",
       " 'lastTrainedDateTime': '2024-08-26T01:22:31.0931633Z',\n",
       " 'lastDeployedDateTime': '2024-08-26T01:58:19Z',\n",
       " 'deploymentExpirationDate': '2026-08-26',\n",
       " 'modelTrainingConfigVersion': '2022-09-01'}"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.get_deployment(\n",
    "    project_name=project_name,\n",
    "    deployment_name=deployment_name\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ConversationAuthoringClient 用于创建和管理对话模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [],
   "source": [
    "from azure.ai.language.conversations import ConversationAnalysisClient\n",
    "client_analyze = ConversationAnalysisClient(endpoint, credential)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [],
   "source": [
    "result=client_analyze.analyze_conversation(\n",
    "    task=analyze_task\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "query: send an email to zhwa\n",
      "project kind: Conversation\n",
      "\n",
      "top intent: SendEmail\n",
      "category: SendEmail\n",
      "confidence score: 0.9123426\n",
      "\n",
      "entities:\n",
      "\n",
      "category: ContactName\n",
      "text: zhwa\n",
      "confidence score: 1\n"
     ]
    }
   ],
   "source": [
    "print(f\"query: {result['result']['query']}\")\n",
    "print(f\"project kind: {result['result']['prediction']['projectKind']}\\n\")\n",
    "\n",
    "print(f\"top intent: {result['result']['prediction']['topIntent']}\")\n",
    "print(f\"category: {result['result']['prediction']['intents'][0]['category']}\")\n",
    "print(f\"confidence score: {result['result']['prediction']['intents'][0]['confidenceScore']}\\n\")\n",
    "\n",
    "print(\"entities:\")\n",
    "for entity in result['result']['prediction']['entities']:\n",
    "    print(f\"\\ncategory: {entity['category']}\")\n",
    "    print(f\"text: {entity['text']}\")\n",
    "    print(f\"confidence score: {entity['confidenceScore']}\")\n",
    "    if \"resolutions\" in entity:\n",
    "        print(\"resolutions\")\n",
    "        for resolution in entity['resolutions']:\n",
    "            print(f\"kind: {resolution['resolutionKind']}\")\n",
    "            print(f\"value: {resolution['value']}\")\n",
    "    if \"extraInformation\" in entity:\n",
    "        print(\"extra info\")\n",
    "        for data in entity['extraInformation']:\n",
    "            print(f\"kind: {data['extraInformationKind']}\")\n",
    "            if data['extraInformationKind'] == \"ListKey\":\n",
    "                print(f\"key: {data['key']}\")\n",
    "            if data['extraInformationKind'] == \"EntitySubtype\":\n",
    "                print(f\"value: {data['value']}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'kind': 'ConversationResult',\n",
       " 'result': {'query': 'send an email to zhwa',\n",
       "  'prediction': {'topIntent': 'SendEmail',\n",
       "   'projectKind': 'Conversation',\n",
       "   'intents': [{'category': 'SendEmail', 'confidenceScore': 0.9123426},\n",
       "    {'category': 'SearchMessages', 'confidenceScore': 0.7338628},\n",
       "    {'category': 'Cancel', 'confidenceScore': 0.7319635},\n",
       "    {'category': 'QueryLastText', 'confidenceScore': 0.71811926},\n",
       "    {'category': 'Reply', 'confidenceScore': 0.6465073},\n",
       "    {'category': 'CheckMessages', 'confidenceScore': 0.6449551},\n",
       "    {'category': 'Confirm', 'confidenceScore': 0.6390207},\n",
       "    {'category': 'AddMore', 'confidenceScore': 0.59963936},\n",
       "    {'category': 'ReadAloud', 'confidenceScore': 0.5687663},\n",
       "    {'category': 'Delete', 'confidenceScore': 0.5621686},\n",
       "    {'category': 'Forward', 'confidenceScore': 0.5085991},\n",
       "    {'category': 'AddFlag', 'confidenceScore': 0.42635846},\n",
       "    {'category': 'ShowNext', 'confidenceScore': 0.3435155},\n",
       "    {'category': 'ShowPrevious', 'confidenceScore': 0.33022463},\n",
       "    {'category': 'None', 'confidenceScore': 0.2995287}],\n",
       "   'entities': [{'category': 'ContactName',\n",
       "     'text': 'zhwa',\n",
       "     'offset': 17,\n",
       "     'length': 4,\n",
       "     'confidenceScore': 1}]}}}"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nlg_bot_business_api",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
